package com.example.shiwu.adapter;

import static androidx.core.content.ContextCompat.startActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DiffUtil;

import com.alibaba.fastjson.JSONException;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.example.shiwu.AlarmListActivity;
import com.example.shiwu.GatherDataActivity;
import com.example.shiwu.R;
import com.example.shiwu.SendReceiveAddActivity;
import com.example.shiwu.SendReceiveImgDetailsActivity;
import com.example.shiwu.db.model.Alarm;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.vo.AlarmVo;
import com.example.shiwu.db.vo.SendVo;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.service.AlarmService;
import com.example.shiwu.service.SendsService;
import com.example.shiwu.util.Callback;
import com.example.shiwu.util.SocketMergeCallBackAlarmUtils;
import com.example.shiwu.util.SocketMergeCallBackUtils;

import java.util.ArrayList;
import java.util.List;

public class AlarmAdapter extends BaseAdapter implements View.OnClickListener {

    private AlarmListActivity mContext;
    private int resourceId;
    public boolean flage = false;
    private List<AlarmVo> listItems;
    private LayoutInflater mInflater;
    private String[] myModaData;
    private Integer checkBoxIDList;            //存储checkBox的值
    private MyClickListener mListener, rListener;
    private static SocketMergeCallBackAlarmUtils socketUtils;
    private Python py;
    private PyObject pyobj;
    private byte[] pydata;
    private SendsService sendsService;
    private DatabaseHelper dbHelper;

    //自定义接口，用于回调按钮点击事件到Activity
    public interface MyClickListener {
        public void clickListener(View v);

        boolean clickRemoveListener(int position);
    }


    public AlarmAdapter(AlarmListActivity mContext, List<AlarmVo> listItems, int resource, String[] modeData,
                        MyClickListener listener) {
        super();
        this.resourceId = resource;
        this.mContext = mContext;
        this.listItems = listItems;
        this.myModaData = modeData;
        this.mListener = listener;
        this.rListener = listener;
        dbHelper = new DatabaseHelper(mContext);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (socketUtils == null) {
                    socketUtils = SocketMergeCallBackAlarmUtils.getInstance(mContext);
                    if (socketUtils != null) {
                        // 启动监听
                        socketUtils.startListening();
                    }else {
                        return;
                    }
                } else {
                    System.out.println("------------SocketMergeCallBackAlarmUtils.resumeThread()------------");
                }
            }
        }).start();

    }


    @SuppressLint("ResourceAsColor")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        final ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(parent.getContext()).inflate(resourceId, parent, false);
            viewHolder = new ViewHolder(view, position);
            viewHolder.device_id.setText(listItems.get(position).getSn());
            viewHolder.send_items_name.setText(listItems.get(position).getName());
            viewHolder.alarm_msg.setText(listItems.get(position).getAlarmMsg());
            viewHolder.send_items_createTime.setText(listItems.get(position).getCreateTime());
            if (listItems.get(position).getStatus() == 1) {
                viewHolder.clear_alarm_sb.setText("报警解除");

                viewHolder.device_id.setTextColor(mContext.getResources().getColor(R.color.text_block));
                viewHolder.device_id_val.setTextColor(mContext.getResources().getColor(R.color.text_block));
            } else {
                viewHolder.device_id.setTextColor(mContext.getResources().getColor(R.color.red1));
                viewHolder.device_id_val.setTextColor(mContext.getResources().getColor(R.color.red1));
            }


            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (AlarmAdapter.ViewHolder) view.getTag();
            viewHolder.device_id.setText(listItems.get(position).getSn());
            viewHolder.send_items_name.setText(listItems.get(position).getName());
            viewHolder.alarm_msg.setText(listItems.get(position).getAlarmMsg());
            viewHolder.send_items_createTime.setText(listItems.get(position).getCreateTime());
            if (listItems.get(position).getStatus() == 1) {
                viewHolder.clear_alarm_sb.setText("报警解除");
                viewHolder.device_id.setTextColor(mContext.getResources().getColor(R.color.text_block));
                viewHolder.device_id_val.setTextColor(mContext.getResources().getColor(R.color.text_block));
            } else {
                viewHolder.device_id.setTextColor(mContext.getResources().getColor(R.color.red1));
                viewHolder.device_id_val.setTextColor(mContext.getResources().getColor(R.color.red1));
            }
        }

        try {
            initPython(parent.getContext());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        viewHolder.clear_alarm_sb.setOnClickListener(new View.OnClickListener() {//清除警告
            @Override
            public void onClick(View v) {
                pydata = pyobj.callAttr("clearAlarm").toJava(byte[].class);
                viewHolder.clear_alarm_sb.setText("报警解除");

                if(socketUtils == null){
                    return;
                }
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        //socketUtils.clear_alram = 1;
                        System.out.println("socketUtils.isSocketConnected() == "+socketUtils.isSocketConnected());
                        if(socketUtils.isSocketConnected()){
                            socketUtils.writeMsgByte(pydata);
                        }

                    }
                }).start();

                viewHolder.device_id.setTextColor(mContext.getResources().getColor(R.color.text_block));
                viewHolder.device_id_val.setTextColor(mContext.getResources().getColor(R.color.text_block));
//                new Thread(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        SocketMergeCallBackAlarmUtils.clear_alram = 1;
//                        SocketMergeCallBackAlarmUtils.writeMsgByte(pydata, new Callback() {
//                            @Override
//                            public void onSuccess(byte[] data) {
//                                Log.i("SocketClient", "报警解除 ============= "+new String(data));
//
//                            }
//                            @Override
//                            public void onFailure(String errorMessage) {
//                                Log.e("SocketClient", "Failed to send text: " + errorMessage);
//                            }
//                        });
//                    }
//                }).start();

                Integer sId = Integer.valueOf(listItems.get(position).getId());
                System.out.println("----------sid-----------" + sId);
                mContext.clearAlarm(sId);
                mContext.updataData();
            }
        });

        viewHolder.delSb.setOnClickListener(new View.OnClickListener() {//删除
            @Override
            public void onClick(View v) {
                System.out.println("id =================================== " + v.getId());
                //点击删除按钮之后，给出dialog提示
                AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                builder.setTitle("确认删除?");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("id =================================== " + position);
                        System.out.println("——————————————删除——————————————————");
                        Integer sId = Integer.valueOf(listItems.get(position).getId());
                        String itemId = String.valueOf(listItems.get(position).getItemId());

                        Alarm sen1 = new Alarm(itemId);
                        sen1.setStatus(2);
                        AlarmService sendService = new AlarmService();
                        Alarm sen2 = new Alarm();
                        sen2.setId(sId);
                        Boolean bool = sendService.updade(sen1, sen2);
                        mContext.updataData();
                    }
                });
                builder.show();
            }
        });
        viewHolder.gatherSb.setOnClickListener(new View.OnClickListener() {//删除
            @Override
            public void onClick(View v) {
                System.out.println("id =================================== " + v.getId());
                sendsService = new SendsService();
                SQLiteDatabase db = dbHelper.getReadableDatabase();
                //Integer sId = Integer.valueOf(listItems.get(position).getId());
                String itemId = String.valueOf(listItems.get(position).getItemId());
                String sendId = String.valueOf(listItems.get(position).getSendId());
                // 查询条件
                String[] projection = {"uid,error_point,error_point_line"}; // 要返回的列
                String selection = "id = ?"; // 查询条件（相当于 WHERE 子句）
                String[] selectionArgs = {sendId}; // 条件参数，会替换上面的 ?
                String sortOrder = "id DESC"; // 排序方式

                // 执行查询
                Cursor cursor = db.query(
                        "tb_sends", // 表名
                        projection,
                        selection,
                        new String[]{sendId},
                        null, // GROUP BY
                        null, // HAVING
                        sortOrder
                );
                List<Sends> lis = new ArrayList<>();
                while (cursor.moveToNext()) {
                    Sends sends = new Sends();
                    String id = cursor.getString(0);
                    sends.setUid(id);
                    String error_point = cursor.getString(1);
                    sends.setErrorPoint(error_point);
                    Integer error_point_line = cursor.getInt(2);
                    sends.setErrorPointLine(error_point_line);
                    lis.add(sends);
                }
                if(lis.size()>0){
                    String senduId = lis.get(0).getUid();
                    String error_point = lis.get(0).getErrorPoint();
                    String error_point_line = String.valueOf(lis.get(0).getErrorPointLine());
                    Intent intent = new Intent(mContext, GatherDataActivity.class);
                    intent.putExtra("senduId", senduId);
                    intent.putExtra("errorPoint", error_point);
                    intent.putExtra("errorPointLine", error_point_line);
                    socketUtils.releaseSocket();
                    mContext.startActivity(intent);
                }

            }
        });
        //viewHolder.checkboxOperateData = (CheckBox) convertView.findViewById(R.id.device_items_checkbox);
        // 根据isSelected来设置checkbox的显示状况
//        if (flage) {
//            holder.checkboxOperateData.setVisibility(View.VISIBLE);
//        } else {
//            holder.checkboxOperateData.setVisibility(View.GONE);
//        }
        //获取复选框选中状态改变事件进行增删改
        viewHolder.alarm_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                /*
                 * b=选中状态
                 * if b = true 将值添加至checkBoxIDList
                 * if b = false 将值从checkBoxIDList移除
                 * */
                Integer itemId = Integer.valueOf(listItems.get(position).getId());
                if (b) {

                    checkBoxIDList = itemId;

                } else {

                    checkBoxIDList = -itemId;

                }
                System.out.println(checkBoxIDList);
                compoundButton.setId(checkBoxIDList);
                mListener.clickListener(compoundButton);
            }
        });

        return view;
    }

    private void initPython(Context myContext) throws JSONException, InterruptedException {
        //初始化python环境
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(myContext));
        }

        py = Python.getInstance();
        pyobj = py.getModule("Send_Param");
    }

    public void cleckAll() {
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return listItems.size();
    }

    @Override
    public Object getItem(int position) {
        return listItems.get(position);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    //响应按钮点击事件,调用子定义接口，并传入View
    @Override
    public void onClick(View v) {
        mListener.clickListener(v);
    }

    class ViewHolder {
        public TextView clear_alarm_sb, delSb, device_id, device_id_val, send_items_name, alarm_msg, send_items_createTime,gatherSb,send_items_gather_sb;
        public CheckBox alarm_checkbox;

        public ViewHolder(View view, int position) {
            device_id = view.findViewById(R.id.device_id_val);
            device_id_val = view.findViewById(R.id.device_id);
            send_items_name = view.findViewById(R.id.send_items_name_val);
            alarm_msg = view.findViewById(R.id.alarm_msg_val);
            send_items_createTime = view.findViewById(R.id.send_items_createTime_val);
            clear_alarm_sb = view.findViewById(R.id.clear_alarm_sb);
            delSb = view.findViewById(R.id.send_items_del_sb);
            gatherSb = view.findViewById(R.id.send_items_gather_sb);
            alarm_checkbox = view.findViewById(R.id.alarm_items_checkbox);
            send_items_gather_sb = view.findViewById(R.id.send_items_gather_sb);
        }

    }

}
